package com.jubaozan.framework.sentinel.listener;

import com.alibaba.fastjson.JSON;
import com.jubaozan.framework.sentinel.config.ApplicationRedisValueConfig;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.api.sync.RedisPubSubCommands;
import java.util.Collection;
import javax.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/7/15 14:34
 */

@Slf4j
@Component
public class RedisRulePublisher {
    private String channel = "sentinel.rules.channel";
    @Autowired
    private ApplicationRedisValueConfig applicationRedisValueConfig;
    private RedisClient client;

    @PostConstruct
    public void  initFlowPropertyListener() {
        RedisURI redisURI =  RedisURI.builder().withHost(applicationRedisValueConfig.getHost())
            .withPort(applicationRedisValueConfig.getPort())
            .withPassword(applicationRedisValueConfig.getPassword())
            .withDatabase(applicationRedisValueConfig.getDatabase())
            .build();
        client = RedisClient.create(redisURI);
    }
    public <T> void pushRules(Collection<T> rules, String ruleKey) {
        StatefulRedisPubSubConnection<String, String> connection = client.connectPubSub();
        RedisPubSubCommands<String, String> subCommands = connection.sync();
        String value = JSON.toJSONString( rules);
        subCommands.multi();
        subCommands.set(ruleKey, value);
        subCommands.publish(channel, value);
        subCommands.exec();
    }

    public <T> void pushConfig(T  rules, String configKey) {
        StatefulRedisPubSubConnection<String, String> connection = client.connectPubSub();
        RedisPubSubCommands<String, String> subCommands = connection.sync();
        String value = JSON.toJSONString( rules);
        subCommands.multi();
        subCommands.set(configKey, value);
        subCommands.publish(channel, value);
        subCommands.exec();
    }
}
